﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack || true)
        {
            //key, WNote, WGBudget, WGMadeIn, WGYear, WGDescription, WGName, 
            //WGAmount, WGApp, WGPId, GCId, WVisible, WTran, HCId, MId, WEnd, WStart, WGBrand
            //Label1.Text = Server.HtmlEncode(TextBox1.Text);
            string sRkey = Request.QueryString["key"];
            string sRWNote = Request.QueryString["WNote"];
            string sRWGBudget = Request.QueryString["WGBudget"];
            string sRWGBudget_min = Request.QueryString["WGBudget_min"];
            string sRWGMadeIn = Request.QueryString["WGMadeIn"];
            string sRWGYear = Request.QueryString["WGYear"];
            string sRWGYear_min = Request.QueryString["WGYear_min"];
            string sRWGDescription = Request.QueryString["WGDescription"];
            string sRWGName = Request.QueryString["WGName"];
            string sRWGAmount = Request.QueryString["WGAmount"];
            string sRWGAmount_min = Request.QueryString["WGAmount_min"];
            string sRWGApp = Request.QueryString["WGApp"];
            string sRGCId = Request.QueryString["GCId"];
            string sRWTran = Request.QueryString["WTran"];
            string sRHCId = Request.QueryString["HCId"];
            string sRMId = Request.QueryString["MId"];
            string sRWEnd = Request.QueryString["WEnd"];
            string sRWStart = Request.QueryString["WStart"];
            string sRWGBrand = Request.QueryString["WGBrand"];
            string strSelColoum = "SELECT [Wid],[WGMadeIn] AS '產地',[WGBrand] AS '製造商',[WGName] AS '產品名稱'";
            string strSelCommand = " FROM [Wanted] where [WVisible]=1";
            string strOrderCommand = " ORDER BY [WEnd] DESC;";

            SDSResult.SelectParameters.Clear();

            //d1.Style.Add(HtmlTextWriterStyle.Display, "block");
            //d1.Style.Add(HtmlTextWriterStyle.Display, "none");
            if (sRkey != null)
            {
                strSelColoum = strSelColoum + ",[WGDescription] AS '商品描述'";
                strSelCommand = strSelCommand + " AND (([WGMadeIn] LIKE '%' + @sRkey + '%')"
                                              + " OR ([WGName] LIKE '%' + @sRkey + '%')"
                                              + " OR ([WGBrand] LIKE '%' + @sRkey + '%')"
                                              + " OR ([WGDescription] LIKE '%' + @sRkey + '%'))";
                SDSResult.SelectParameters.Add("sRkey", sRkey);
            }
            else
            {
                //sample
                if (sRWNote != null)
                {
                    strSelColoum = strSelColoum + ",[WNote] AS '備註'";
                    strSelCommand = strSelCommand + " AND ([WNote] LIKE '%' + @sRWNote + '%')";
                    SDSResult.SelectParameters.Add("sRWNote", sRWNote);
                }
                if (sRWGMadeIn != null)
                {
                    strSelCommand = strSelCommand + " AND ([WGMadeIn] LIKE '%' + @WGMadeIn + '%')";
                    SDSResult.SelectParameters.Add("WGMadeIn", sRWGMadeIn);
                }
                if ((sRWGYear_min != null) && (sRWGYear == null))
                    sRWGAmount = "2100/12";
                if (sRWGYear != null)
                {
                    strSelColoum = strSelColoum + ",[WGYear] AS '製造年份'";
                    if (sRWGBudget_min == null)
                        sRWGYear_min = "1901/01";
                    strSelCommand = strSelCommand + " AND ([WGYear] <= @WGYear)"
                                                  + " AND ([WGYear_min] >= @WGYear_min)";
                    SDSResult.SelectParameters.Add("WGYear", sRWGYear);
                    SDSResult.SelectParameters.Add("WGYear_min", sRWGYear_min);
                }
                if (sRWGDescription != null)
                {
                    strSelColoum = strSelColoum + ",[WGDescription] AS '商品描述'";
                    strSelCommand = strSelCommand + " AND ([WGDescription] LIKE '%' + @WGDescription + '%')";
                    SDSResult.SelectParameters.Add("WGDescription", sRWGDescription);
                }
                if (sRWGName != null)
                {
                    strSelCommand = strSelCommand + " AND ([WGName] LIKE '%' + @WGName + '%')";
                    SDSResult.SelectParameters.Add("WGName", sRWGName);
                }
                if (IsNumeric(sRWGAmount_min) && !IsNumeric(sRWGAmount))
                    sRWGAmount = "2147483647";
                if (IsNumeric(sRWGAmount))
                {
                    if (!IsNumeric(sRWGBudget_min))
                        sRWGBudget_min = "1";
                    strSelColoum = strSelColoum + ",[WGAmount] AS '需求數量'";
                    strSelCommand = strSelCommand + " AND ([WGAmount] <= @WGAmount)"
                                                  + " AND ([WGBudget_min] >= @WGBudget_min)";
                    SDSResult.SelectParameters.Add("WGAmount", sRWGAmount);
                    SDSResult.SelectParameters.Add("WGBudget_min", sRWGBudget_min);
                }
                if (sRWGApp != null)
                {
                    strSelColoum = strSelColoum + ",[WGApp] AS '用途'";
                    strSelCommand = strSelCommand + " AND ([WGApp] LIKE '%' + @WGApp + '%')";
                    SDSResult.SelectParameters.Add("WGApp", sRWGApp);
                }
                if (IsNumeric(sRGCId))
                {
                    strSelColoum = strSelColoum + ",[GCId] AS '商品分類'";
                    strSelCommand = strSelCommand + " AND ([GCId] = @GCId )";
                    SDSResult.SelectParameters.Add("GCId", sRGCId);
                }
                if (sRWTran != null)
                {
                    strSelColoum = strSelColoum + ",[WTran] AS '交易方式'";
                    strSelCommand = strSelCommand + " AND ([WTran] LIKE '%' + @WTran + '%')";
                    SDSResult.SelectParameters.Add("WTran", sRWTran);
                }
                if (IsNumeric(sRHCId))
                {
                    strSelColoum = strSelColoum + ",[HCId] AS '交易狀態'";
                    strSelCommand = strSelCommand + " AND ([HCId] = @HCId )";
                    SDSResult.SelectParameters.Add("HCId", sRHCId);
                }
                if (IsNumeric(sRMId))
                {
                    strSelCommand = strSelCommand + " AND ([MId] = @MId )";
                    SDSResult.SelectParameters.Add("MId", sRMId);
                }
                if (sRWEnd != null && sRWStart == "")
                    sRWStart = DateTime.Now.ToShortDateString().ToString();
                if (sRWStart != null)
                {
                    if (sRWEnd == null)
                        sRWEnd = DateTime.Now.ToShortDateString().ToString();
                    strSelColoum = strSelColoum + ",[WStart] AS '開始日',[WEnd] AS '結束日'";
                    strSelCommand = strSelCommand + " AND ([WStart] <= @sRWStart)"
                                                  + " AND ([WEnd] >= @sRWEnd)";
                    SDSResult.SelectParameters.Add("sRWStart", sRWStart);
                    SDSResult.SelectParameters.Add("sRWEnd", sRWEnd);
                }
                if (sRWGBrand != null)
                {
                    strSelCommand = strSelCommand + " AND ([WGBrand] LIKE '%' + @WGBrand + '%')";
                    SDSResult.SelectParameters.Add("WGBrand", sRWGBrand);
                }
            }
            //tbDeBug.Text = strSelColoum + strSelCommand + strOrderCommand;
            SDSResult.SelectCommand = strSelColoum + strSelCommand + strOrderCommand;
            HyperLinkField hlf = new HyperLinkField();
            string[] dataNavigateUrlFields = { "Wid" };
            hlf.DataNavigateUrlFields = dataNavigateUrlFields;
            hlf.DataNavigateUrlFormatString = "wDetail.aspx?id={0}";
            hlf.HeaderText = "詳細內容";
            hlf.Text = "查看";
            GVResult.Columns.Add(hlf);
        }
    }
    public static System.Boolean IsNumeric(System.Object Expression)
    {
        if (Expression == null || Expression is DateTime)
            return false;
        if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
            return true;
        try
        {
            if (Expression is string)
                Double.Parse(Expression as string);
            else
                Double.Parse(Expression.ToString());
            return true;
        }
        catch { } // just dismiss errors but return false
        return false;
    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["mid"] == null)//會員
            this.Page.MasterPageFile = "~/MasterPage.master";
        else       //一般使用者
            this.Page.MasterPageFile = "~/LoginedMasterPage.master";
    }

    /*protected void DBInit()
    {
        //== SqlDataSource精靈   自動產生的SQL指令，可以當作參考 == 
        SqlDataSource1.SelectParameters.Clear();

        //==以下是自己改寫的「多重欄位 搜尋引擎」，SQL指令的文字組合 == 
        string mySQLstr = " 1=1 ";   //請注意， 1=1後面多一個空白！ 

        if (TextBox1.Text != null)
        {
            mySQLstr = mySQLstr + " AND ([title] LIKE '%' + @title + '%')";
            //== 重點在此：參數必須寫在IF判別式這裡，不能一起寫在後面。== 
            SqlDataSource1.SelectParameters.Add("title", TextBox1.Text);
        }
        
        if (TextBox2.Text != null)
        {
            mySQLstr = mySQLstr + " AND ([summary] LIKE '%' + @summary + '%')";
            SqlDataSource1.SelectParameters.Add("summary", TextBox2.Text);
        }

        if (TextBox3.Text != null)
        {
            mySQLstr = mySQLstr + " AND ([article] LIKE '%' + @article + '%')";
            SqlDataSource1.SelectParameters.Add("article", TextBox3.Text);
        }

        //============================================ 
        //== SqlDataSource1 資料庫的連接字串 ConnectionString， 
        //== 已事先寫在「HTML畫面的設定」裡面 == 
        //============================================ 

        //== 最後，合併成完整的SQL指令（搜尋引擎～專用） == 
        SqlDataSource1.SelectCommand = "SELECT * FROM [test] WHERE " + mySQLstr;

        //================================================== 
        //== 執行SQL指令 與 GridView1.DataBind()的部份，均已經事先寫好 
        //==在「HTML畫面的設定」上，也就是下面這一行，就通通搞定了。ASP.NET 真強！ 
        //==<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1"> 
        //================================================== 

        Response.Write("<hr>您要搜尋哪些欄位？SQL指令為  " + SqlDataSource1.SelectCommand + "<hr>");
        //== 重點在此：參數必須寫在上面的「每一個IF判別式」裡面，不能一起寫在這邊。== 
        //== 否則，這裡有出現的參數，就必須有「值」，不能留白！ == 
        //SqlDataSource1.SelectParameters.Add("title", TextBox1.Text); 
        //SqlDataSource1.SelectParameters.Add("summary", TextBox2.Text); 
        //SqlDataSource1.SelectParameters.Add("article", TextBox3.Text); 

        //== 執行SQL指令 .select() == 
        //DataView dv = SqlDataSource1.Select(new DataSourceSelectArguments); 

        //GridView1.DataSource = dv; 
        //GridView1.DataBind(); 
        //============================================ 
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(GridView1.PageIndex) != 0)
        {
           //==如果不加上這行IF判別式，假設當我們看第四頁時， 
           //==又輸入新的條件，重新作搜尋。「新的」搜尋結果將會直接看見 "第四頁"！這個問題發生在這裡，請看！=== 
           GridView1.PageIndex = 0;
        }

        DBInit();
    }

    protected void  GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
            GridView1.PageIndex = e.NewPageIndex;

            Response.Write("目前位於第" + (Convert.ToInt32(e.NewPageIndex) + 1) + "頁<br>");
            //== 把 GridView1 的 [EnableSortingAndPagingCallBack]屬性關閉(=False)，才會執行到這一行！ == 
    }

    protected void  GridView1_PageIndexChanged(object sender, EventArgs e)
    {
        DBInit();
    }*/

    /*private static void ReadOrderData(string connectionString)
    {
        string queryString ="SELECT OrderID, CustomerID FROM dbo.Orders;";
        using (SqlConnection connection =new SqlConnection(connectionString))
        {
            SqlCommand command =new SqlCommand(queryString, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            // Call Read before accessing data.
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",reader[0], reader[1]));
            }
            // Call Close when done reading.
            reader.Close();
        }
    }*/
    /*  using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.Add("@ID", SqlDbType.Int);
            command.Parameters["@ID"].Value = customerID;

            // Use AddWithValue to assign Demographics.
            // SQL Server will implicitly convert strings into XML.
            command.Parameters.AddWithValue("@demographics", demoXml);

            try
            {
                connection.Open();
                Int32 rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine("RowsAffected: {0}", rowsAffected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }*/
    /*private static void CreateCommand(string queryString,string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandTimeout = 15;
            command.CommandType = CommandType.Text;
            command.CommandText = queryString;

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",reader[0], reader[1]));
            }
        }
    }*/
    protected void ddlDetail_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlDetail.SelectedIndex == 0)
        {
            btnKey.Enabled = true;
            divDetail.Style.Add(HtmlTextWriterStyle.Display, "none");
        }
        else
        {
            btnKey.Enabled = false;
            divDetail.Style.Add(HtmlTextWriterStyle.Display, "block");
        }
    }
    protected void btnKey_Click(object sender, EventArgs e)
    {
        if (ddlDetail.SelectedIndex == 0)
        {
            Response.Redirect("WantedList.aspx?key=" + tbkey.Text);
        }
    }
}